package work.comeback.omo.controller.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@WebFilter(
        filterName = "ResourceFilter", urlPatterns = {"/error/*"}, asyncSupported = true,
        initParams = {
                @WebInitParam(name = "styleHref", value = "assets"),
        },
        description = "Catch all request setting some config."
)
public class ResourceFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(ResourceFilter.class);
    private String styleHref;
    private String basePath;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        styleHref = filterConfig.getInitParameter("styleHref");
        basePath = filterConfig.getServletContext().getContextPath();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        // basePath attribute
        httpRequest.setAttribute("basePath", basePath);
        httpRequest.setAttribute("styleHref", styleHref);
        // encoding
        String encoding = httpRequest.getCharacterEncoding();
        if (!encoding.equalsIgnoreCase("UTF-8")) {
            httpRequest.setCharacterEncoding("UTF-8");
        }
        // do next filter
        chain.doFilter(request, response);
    }
}
